import random

from flask import request, jsonify, session, redirect, url_for, make_response, g
from werkzeug.security import generate_password_hash, check_password_hash

from models import db
from models.index import User
from utils.sms_aliyun import send_msg_to_phone
from views import passport_bp


@passport_bp.route('/register', methods=['GET', 'POST'])
def register():
    mobile = request.json.get("mobile")
    password = request.json.get("password")
    # image_code = request.json.get("image_code")
    smscode = request.json.get("smscode")
    # image = session.get('image_code')
    if_user = db.session.query(User).filter(User.mobile == mobile).first()
    if len(mobile) != 11:
        ret = {
            'errno': 1004,
            'errmsg': '请输入正确的手机号'
        }
        return jsonify(ret)

    if if_user:
        ret = {
            'errno': 1001,
            'errmsg': '该手机号已经存在!'
        }
        return jsonify(ret)
    if session.get("sms_code") != smscode:
        ret = {
            "errno": 1003,
            "errmsg": "重新输入手机验证码"
        }

    # elif image_code.lower() != image.lower():
    #     ret = {
    #         'errno': 1002,
    #         'errmsg': '验证码不正确!'
    #     }
    else:
        user = User()
        user.nick_name = mobile
        user.password_hash = generate_password_hash(password)
        user.mobile = mobile
        try:
            db.session.add(user)
            db.session.commit()
            session['user_id'] = user.id
            session['nick_name'] = mobile
            ret = {
                'errno': 0,
                'errmsg': '注册成功'
            }

        except Exception as ret1:
            db.session.rollback()
            ret = {
                'errno': 1003,
                'errmsg': '注册失败,请重试！'
            }

    return jsonify(ret)


@passport_bp.route('/login', methods=['GET', 'POST'])
def login():
    mobile = request.json.get('mobile')
    password = request.json.get('password')
    user = db.session.query(User).filter(User.mobile == mobile).first()
    if user and check_password_hash(user.password_hash, password):
        ret = {
            'errno': 0,
            'errmsg': '登录成功'
        }
        session['user_id'] = user.id
        session['nick_name'] = mobile
    else:
        ret = {
            'errno': 2001,
            'errmsg': '用户名或密码错误!'

        }
    return jsonify(ret)


@passport_bp.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('index.index'))


@passport_bp.route("/image_code")
def image_code():
    if not g.user:
        return redirect(url_for("index.index"))
    from utils.captcha.captcha import captcha

    # 生成验证码
    # hash值  验证码值  图片内容
    name, text, image = captcha.generate_captcha()

    session['image_code'] = text

    # 返回响应内容
    resp = make_response(image)
    resp.headers['Content-Type'] = 'image/png'

    return resp


@passport_bp.route('/smscode', methods=['POST'])
def sms_code():
    # 1. 提取数据
    if not g.user:
        return redirect(url_for("index.index"))
    image_code = request.json.get("image_code")
    mobile = request.json.get("mobile")

    # 2. 校验图片验证码是否正确
    image_code_session = session.get("image_code")
    # print("输入的验证码", image_code)
    # print("生成的验证码", image_code_session)
    if image_code.lower() != image_code_session.lower():
        ret = {
            "errno": 4004,
            "errmsg": "图片验证码错误..."
        }
        return jsonify(ret)

    # 3. 生成一个随机的6位数
    sms_code = str(random.randint(100000, 999999))
    # print("短信验证码是:", sms_code)

    # 4. 存储到session中
    session['sms_code'] = sms_code

    # 5. 通过短信发送这个6位数
    send_msg_to_phone(mobile, sms_code)

    ret = {
        "errno": 0,
        "errmsg": "发送短信验证码成功..."
    }

    return jsonify(ret)
